package handler;

import org.apache.ibatis.datasource.pooled.PooledDataSource;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;

public class MysqlHandler {

    private static SqlSessionFactory sqlSessionFactory;

    public static SqlSession getSqlSession(String ip, String port, String database, String username, String password) {
        // 数据源配置
        PooledDataSource dataSource = new PooledDataSource();
        dataSource.setDriver("com.mysql.cj.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://" + ip + ":" + port + "/" + database + "?useSSL=false&serverTimezone=UTC");
        dataSource.setUsername(username);
        dataSource.setPassword(password);

        // 事务工厂
        JdbcTransactionFactory transactionFactory = new JdbcTransactionFactory();

        // 环境配置
        Environment environment = new Environment("development", transactionFactory, dataSource);

        // MyBatis配置
        Configuration configuration = new Configuration(environment);

        // 构建SqlSessionFactory
        try {
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
        } catch (Exception e) {
            return null;
        }
        return sqlSessionFactory.openSession();
    }
}

